package db

import (
	"fmt"

	"github.com/glebarez/sqlite"
	"gorm.io/gorm"
)

// 数据库实例对象
var DB *gorm.DB

func InitDB() *gorm.DB {
	if DB != nil {
		return DB
	}
	config := &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true,
	}
	db, err := gorm.Open(sqlite.Open("goMyAdmin.db"), config)
	if err != nil {
		panic("failed to connect database")
	}
	DB = db
	initCreateTable(db)
	return db
}

// 初始化创建表
func initCreateTable(db *gorm.DB) {
	db.Migrator().DropTable(&Server{})
	db.Migrator().DropTable(&User{})
	isExist := db.Migrator().HasTable(&User{})
	if isExist {
		return
	}
	fmt.Println(isExist, "是否存在用户表")

	db.AutoMigrate(&User{})
	db.AutoMigrate(&Server{})

	id, err := AddUser(&User{Name: "admin", Email: "admin", Password: "123456"})
	fmt.Println(id, err)

	SaveOneServerRecord(&Server{IP: "127.0.0.1", UserId: id, Port: 3306, User: "root", Password: "root", Database: "mysql", Name: "test-local"})
	// db.AutoMigrate(&User{})
	// db.Create(&User{Name: "admin", Email: "admin", Password: "123456"})
}
